﻿/*
 * Copyright (C) Alibaba Cloud Computing
 * All rights reserved.
 * 
 * 版权所有 （C）阿里云计算有限公司
 */

using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Aliyun.OpenServices.Common.Utilities
{
    internal static class HttpUtils
    {
        public const string Utf8Charset = "utf-8";
        public const string Iso88591Charset = "iso-8859-1";
        private const string UrlAllowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

        public static string ConbineQueryString(IEnumerable<KeyValuePair<string, string>> parameters)
        {
            var isFirst = true;
            var queryString = new StringBuilder();

            foreach (var p in parameters)
            {
                if (!isFirst)
                    queryString.Append("&");                
                
                isFirst = false;

                queryString.Append(p.Key);
                if (!string.IsNullOrEmpty(p.Value))
                    queryString.Append("=").Append(EncodeUri(p.Value, Utf8Charset));
            }

            return queryString.ToString();
        }
        
        public static string EncodeUri(string uriToEncode, string charset)
        {
            if (string.IsNullOrEmpty(uriToEncode))
                return string.Empty;

            const string escapeFlag = "%";
            var encodedUri = new StringBuilder(uriToEncode.Length * 2);
            var bytes = Encoding.GetEncoding(charset).GetBytes(uriToEncode);
            foreach (var b in bytes)
            {
                char ch = (char)b;
                if (UrlAllowedChars.IndexOf(ch) != -1)
                    encodedUri.Append(ch);
                else
                {
                    encodedUri.Append(escapeFlag).Append(
                        string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)b));
                }
            }

            return encodedUri.ToString();
        }

        public static string Reencode(string data, string fromCharset, string toCharset)
        {
            if (string.IsNullOrEmpty(data))
                return string.Empty;

            var bytes = Encoding.GetEncoding(fromCharset).GetBytes(data);
            return Encoding.GetEncoding(toCharset).GetString(bytes);
        }
    }
}
